<?php

namespace Home\Controller;

use Home\Core\CommandSDK;

class DeviceListController extends BaseController
{

    /**
     * 检索设备列表
     *
     */
    public function device_list()
    {
        $param = I('get.');
        if($_SESSION['AreaId'] !== null){
            $param['areaid']=$_SESSION['AreaId'];
        }
        if(empty(I('pageid'))){
            $param['pageid']=1;
        }else{
            $param['pageid']=I('pageid');
        }
        if(empty(I('pagecount'))){
            $param['pagecount']=10;
        }else{
            $param['pagecount']=I('pagecount');
        }
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::IntercomLists, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $pageid=$param['pageid'];
        $pagecount=$param['pagecount'];
        $totnum=$return->totnum;
        $pagenum=$totnum/$pagecount;
        $this->assign('pageid', $pageid);//页数
        $this->assign('pagecount', $pagecount);//每页显示条数
        $this->assign('pagenum', $pagenum);//总页数
        $this->assign('totnum', $totnum); //总条数
        $this->assign('array', $array);
        $this->assign('param', $param);
        $cookie = base64_decode($_COOKIE['user_info']);   // 解析cookie
        parse_str($cookie,$userinfo);
        if($userinfo['userrole'] == '2'){
            $this->assign('userrole',$userinfo['userrole']);
            $this->assign('areaname',$_SESSION['AreaName']);
            $this->assign('areaid',$_SESSION['AreaId']);
        }
        $this->display();
    }

    /**
     * 修改设备
     */
    public function ModifyIntercom_post()
    {
        $date = I('post.');
        $deviceid=$date['deviceid'];
        unset($date['deviceid']);
        $date['hardwaretype']=$date['hardwaretype']*1;
        $date['channelcnt']=$date['channelcnt']*1;
        $date['protocoltype']=$date['protocoltype']*1;
        $date['authenticatetype']=$date['authenticatetype']*1;
        $param['updateinfo']=urlencode(json_encode($date));
        $param['deviceid']=$deviceid;
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::ModifyIntercom, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 删除设备
     */
    public function DelIntercom_post()
    {
        $param = I('post.');
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::DelIntercom, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 添加设备
     */
    public function AddIntercom_post()
    {
        $date = I('post.');
//        dump($date);
        if($_SESSION['AreaId'] !== null){
            $date['areaid']=$_SESSION['AreaId'];
        }
        $date['areaid']=$date['areaid']*1;
        $date['hardwaretype']=$date['hardwaretype']*1;
        $date['channelcnt']=$date['channelcnt']*1;
        $date['protocoltype']=$date['protocoltype']*1;
        $date['authenticatetype']=$date['authenticatetype']*1;
        $param['device']=urlencode(json_encode($date));
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::AddIntercom, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 检索设备详情列表
     */
  	public function device_list_xq()
    {
        $param = I('get.');
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::DetailsIntercom, $param, 'GET');
        $array = json_decode(json_encode($return), true);
//        dump($array);
        $ability='';
        foreach ($array['device']['channels'] as $key => $value) {
            $abilityArr = [];
            if (($value['ability'] & 0x00000001)) {
                $ability = '主码流,';
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000001');
            }
            if (($value['ability'] & 0x00000002)) {
                $ability .= "子码流,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000002');
            }
            if ($value['ability'] & 0x00000004) {
                $ability .= "云台,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000004');
            }
            if ($value['ability'] & 0x00000008) {
                $ability .= "语音,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000008');
            }
            if ($value['ability'] & 0x00000010) {
                $ability .= "对讲,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000010');
            }
            if ($value['ability'] & 0x00000020) {
                $ability .= "WIFI探针,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000020');
            }
            if ($value['ability'] & 0x00000040) {
                $ability .= "农业传感,";
                $array['device']['channels'][$key]['ability']=$ability;
                array_push($abilityArr,'0x00000040');
            }
            $ability='';
            $array['device']['channels'][$key]['abilityArr'] = $abilityArr;
        }
        $this->assign('param', $param);
        $this->assign('array', $array['device']);
        $this->display();

    }

    /**
     * 修改资源
     */
    public function ConfigResources()
    {
        $param = I('post.');
        $sum=0;
        $arr=explode(',',$param['ability']);
        foreach($arr as $value){
            $sum+=$value;
        }
        $param['ability']=$sum;
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::ConfigResources, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 获取资源授权用户
     */
    public function getAuthorizationUser()
    {
        $param = I('post.');
        if($_SESSION['AreaId'] !== null){
            $param['areaid']=$_SESSION['AreaId'];
        }
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::getAuthorizationUser, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 修改资源授权用户信息
     */
    public function ModifyAuthorizationUser()
    {
        $param = I('post.');
        foreach ($param['accounts'] as $key => $value) {
            $param['accounts'][$key]['authaccountid']=$value['authaccountid']*1;
            $param['accounts'][$key]['privilege']=$value['privilege']*1;
        }
        if($param['accounts']==null){
            unset($param['accounts']);
        }else{
            $param['accounts'] = json_encode($param['accounts']);
        }
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::ModifyAuthorizationUser, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 报警时间选择的星期
     */
    protected $week = [
        '0'=>'星期日',
        '1'=>'星期一',
        '2'=>'星期二',
        '3'=>'星期三',
        '4'=>'星期四',
        '5'=>'星期五',
        '6'=>'星期六',
    ];

    /**
     * 报警类型
     */
    protected $type = [
        '1'=>'移动侦测',
        '2'=>'入侵检测',
        '3'=>'视频丢失',
        '4'=>'I/O报警',
        '5'=>'视频遮盖',
        '6'=>'人脸识别',
        '7'=>'物品遗失',
    ];

    /**
     *获取资源事件配置
     */
    public function device_list_bj()
    {
        $param = I('get.');
        $param['resids']=$param['resids'].',';
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::GetResourceAllocation, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        if($array['result']){   // 获取报警配置信息失败（接口调试，如不需要可删除）
            $msg = $sdk::error_code[$array['result']];
            echo '<script type="text/javascript" src="/Public/layui/layui.all.js"></script>';
            echo "<script type='text/javascript'>layer.msg('".$msg."',{icon:2,time:2000})</script>";
        }
        $weektime = $array['eventcfgs']['0']['weektime'];
        $initial_time = [];   // 初始化原有的报警时间
        foreach($weektime as &$week){   // 处理报警时间
            $week['endtime'] = $week['begintime']+$week['livelong'];
            array_push($initial_time,$week);
            $week['time_json'] = json_encode($week);
            $week['day_new'] = $this->week[$week['day']];
            $week['begintime_new'] = $this->secondToTime($week['begintime']);
            $week['endtime_new'] = $this->secondToTime($week['begintime']+$week['livelong']);
        }
        // 处理联动动作
        $linkcfginfo = array_merge($array['eventcfgs']['0']['linkcfginfo']['rec'],$array['eventcfgs']['0']['linkcfginfo']['snap']);
        // 按照resid进行排序
        foreach($linkcfginfo as $key=>&$link){
            $link['type'] = $link['rectime'] ? 'rec' : 'snap';
            $link['type_text'] = $link['rectime'] ? '录像' : '抓图';
            $link['link_json'] = json_encode($link,JSON_UNESCAPED_UNICODE);
            $resid[$key] = $link['resid'];
        }
        array_multisort($resid,SORT_ASC,$linkcfginfo);
        // 报警类型
        $type = explode(',',$array['eventcfgs']['0']['type']);

        $this->assign('weektime',$weektime);
        $this->assign('linkcfginfo',$linkcfginfo);
        $this->assign('initial_time',json_encode($initial_time));
        $this->assign('initial_rec',json_encode($array['eventcfgs']['0']['linkcfginfo']['rec']));
        $this->assign('initial_snap',json_encode($array['eventcfgs']['0']['linkcfginfo']['snap']));
        $this->assign('type', array_filter($type));
        $this->assign('active', $array['eventcfgs']['0']['active']);
        $this->assign('type_arr',$this->type);
        $this->display();
    }

    /**
     * 秒数转换成时间（规则：01:05 => (1*3600)+(5*60)）
     * @param string $time 秒数
     * @return $result 时间
     */
    protected function secondToTime($time)
    {
        $h = floor($time/3600);
        $i = ($time%3600)/60;
        // 两位数
        $h = substr(strval($h+100),1,2);
        $i = substr(strval($i+100),1,2);
        return $h.':'.$i;
    }

    /**
     * 设置资源事件配置
     */
    public function SettingResourceAllocation()
    {
        $param['eventcfg'] = I('post.');
        $param['eventcfg']['resid']=$param['eventcfg']['resid']*1;
        $param['eventcfg']['active']=$param['eventcfg']['active']*1;
        foreach ($param['eventcfg']['weektime'] as $key=>$value){
            $param['eventcfg']['weektime'][$key]['day']=$value['day']*1;
            $param['eventcfg']['weektime'][$key]['begintime']=$value['begintime']*1;
            $param['eventcfg']['weektime'][$key]['endtime']=$value['endtime']*1;
            $param['eventcfg']['weektime'][$key]['livelong']=$value['livelong']*1;
        }
        foreach ($param['eventcfg']['rec'] as $key=>$value){
            $param['eventcfg']['rec'][$key]['resid']=$value['resid']*1;
            $param['eventcfg']['rec'][$key]['rectime']=$value['rectime']*1;
            $param['eventcfg']['rec'][$key]['streamType']=$value['streamType']*1;
            $param['eventcfg']['rec'][$key]['snappicnum']=$value['snappicnum']*1;
            $param['eventcfg']['rec'][$key]['snaptimediff']=$value['snaptimediff']*1;
        }
        foreach ($param['eventcfg']['snap'] as $key=>$value){
            $param['eventcfg']['snap'][$key]['resid']=$value['resid']*1;
            $param['eventcfg']['snap'][$key]['snappicnum']=$value['snappicnum']*1;
            $param['eventcfg']['snap'][$key]['snaptimediff']=$value['snaptimediff']*1;
            $param['eventcfg']['snap'][$key]['streamType']=$value['streamType']*1;
        }
        $param['eventcfg']['linkcfginfo'] = [
            'rec'=>$param['eventcfg']['rec'],
            'snap'=>$param['eventcfg']['snap'],
        ];
        unset($param['eventcfg']['rec']);
        unset($param['eventcfg']['snap']);
        $param['eventcfg']=json_encode($param['eventcfg']);
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::SettingResourceAllocation, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

    /**
     * 获取特定资源
     */
    public function getSpecificResources()
    {
        $param = I('post.');
        if($_SESSION['AreaId'] !== null){
            $param['areaid']=$_SESSION['AreaId'];
        }
        $sdk = new CommandSDK();
        $return = $this->http_request($sdk::getSpecificResources, $param, 'GET');
        $array = json_decode(json_encode($return), true);
        $array['msg']=$sdk::error_code[$return->result];
        $this->ajaxReturn($array);
    }

}